package com.skydoves.chatgpt.core.data.repository

import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import com.skydoves.chatgpt.core.model.network.ChatResponse
import com.skydoves.chatgpt.core.model.network.CreateBotResponse
import com.skydoves.chatgpt.core.model.network.LoginResponse
import com.skydoves.chatgpt.core.model.network.SigninResponse
import com.skydoves.chatgpt.core.network.service.UserService
import com.squareup.moshi.Moshi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
import javax.inject.Inject

class AppUserRepositoryImpl @Inject constructor(
  private val userService: UserService,
  private val dataStore: DataStore<Preferences>,
  private val moshi: Moshi // 注入 Moshi 实例

) :AppUserRepository{

  companion object {
    private val IS_LOGGED_IN_KEY = booleanPreferencesKey("is_logged_in")
    private val UID_KEY = stringPreferencesKey("uid")
  }

  suspend fun initializeUserData() {
    dataStore.edit { preferences ->
      preferences[IS_LOGGED_IN_KEY] = false
      preferences[UID_KEY] = ""  // 默认的 uid 为空字符串
    }
  }

  // 读取 isLoggedIn 的值
  val isLoggedInFlow: Flow<Boolean> = dataStore.data.map { preferences ->
    preferences[IS_LOGGED_IN_KEY] ?: false
  }

  // 读取 uid 的值
  override val uidFlow: Flow<String?> = dataStore.data.map { preferences ->
    preferences[UID_KEY] ?:""
  }

  private suspend fun updateLoginStatus(uid: String, isLoggedIn: Boolean) {
    dataStore.edit { preferences ->
      preferences[IS_LOGGED_IN_KEY] = isLoggedIn
      preferences[UID_KEY] = uid
    }

  }


  override suspend fun login(username: String, password: String): LoginResponse? {
    return withContext(Dispatchers.IO) {
      val response = userService.login(username, password)

      if (response.isSuccessful) {
        response.body()?.also { loginResponse ->
          // 打印返回的消息和状态
          println("Login successful: ${loginResponse.message}, Status: ${loginResponse.status}")
          updateLoginStatus(username,true)

        } ?: run {
          // 如果是字符串，尝试用 Moshi 转换
          response.errorBody()?.string()?.let { jsonString ->
            val adapter = moshi.adapter(LoginResponse::class.java)
            adapter.fromJson(jsonString)?.also { errorResponse ->
              println("Login json failed: ${errorResponse.message}, Status: ${errorResponse.status}")
            }
          }
        }
      } else {
        println("Login request failed with status code: ${response.code()}")
        null
      }
    }
  }


  override suspend fun signin(username: String, password: String): SigninResponse? {
    return withContext(Dispatchers.IO) {
      val response = userService.signin(username, password)

      if (response.isSuccessful) {
        response.body()?.also { signinResponse ->
          // 打印返回的消息和状态
          println("Signin successful: ${signinResponse.message}, Status: ${signinResponse.status}")
        } ?: run {
          // 如果是字符串，尝试用 Moshi 转换
          response.errorBody()?.string()?.let { jsonString ->
            val adapter = moshi.adapter(SigninResponse::class.java)
            adapter.fromJson(jsonString)?.also { errorResponse ->
              // 打印错误消息和状态
              println("Signin failed: ${errorResponse.message}, Status: ${errorResponse.status}")
            }
          }
        }
      } else {
        println("Signin request failed with status code: ${response.code()}")
        null
      }
    }
  }

  override suspend fun chat(username: String, botId: String, question: String, conversationId:String): ChatResponse? {
    return withContext(Dispatchers.IO) {
      val response = userService.chat(username,botId,question,conversationId)

      if (response.isSuccessful) {
        response.body()?.also { ChatResponse ->
          // 打印返回的消息和状态
          println("chat successful: ${ChatResponse.data}, Status: ${ChatResponse.status}")
        } ?: run {
          // 如果是字符串，尝试用 Moshi 转换
          response.errorBody()?.string()?.let { jsonString ->
            val adapter = moshi.adapter(ChatResponse::class.java)
            adapter.fromJson(jsonString)?.also { errorResponse ->
              // 打印错误消息和状态
              println("chat failed: ${errorResponse.data}, Status: ${errorResponse.status}")
            }
          }
        }
      } else {
        println("Signin request failed with status code: ${response.code()}")
        null
      }
    }
  }

  override suspend fun createBot(
    username: String,
    botName: String,
    botDescription: String,
    prompt: String
  ): CreateBotResponse? {
    return withContext(Dispatchers.IO){

      val response = userService.createBot(username,botName,botDescription,prompt)

      if (response.isSuccessful) {
        response.body()?.also { createBotResponse ->
          // 打印返回的消息和状态
          println("create bot successful: ${createBotResponse.botId}, Status: ${createBotResponse.status}")
        } ?: run {
          // 如果是字符串，尝试用 Moshi 转换
          response.errorBody()?.string()?.let { jsonString ->
            val adapter = moshi.adapter(CreateBotResponse::class.java)
            adapter.fromJson(jsonString)?.also { errorResponse ->
              // 打印错误消息和状态
              println("create bot failed: Status: ${errorResponse.status}")
            }
          }
        }
      } else {
        println("create bot failed with status code: ${response.code()}")
        null
      }
    }
  }

}